/*
 *  Copyright 2013 Utkin Dmitry
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include "RpcController.h"

namespace protoqtrpc {

RpcController::RpcController():
    mFailed(false), mCanceled(false), mOnCancel(NULL), mPeerInfo(NULL)
{
}

RpcController::~RpcController()
{
    Reset();
}

void RpcController::Reset()
{
    // This should expire all ongoing requests.
    mCanceled = false;
    mFailed = false;
    delete mOnCancel;
    mOnCancel = NULL;
    mErrorText.clear();
}

bool RpcController::Failed() const
{
    return mFailed;
}

std::string RpcController::ErrorText() const
{
    return mErrorText;
}

void RpcController::SetFailed(const std::string& reason)
{
    mFailed = true;
    mErrorText = reason;
}

void RpcController::StartCancel()
{
    mCanceled = true;
    if (mOnCancel)
        mOnCancel->Run();
}

bool RpcController::IsCanceled() const
{
    return mCanceled;
}

void RpcController::NotifyOnCancel(::google::protobuf::Closure* callback)
{
    Q_ASSERT(!mOnCancel); // must be called only once per request

    mOnCancel = callback;
    if (mCanceled)
        callback->Run();
}

const PeerInfo* RpcController::peerInfo() const
{
    return mPeerInfo;
}

void RpcController::setPeerInfo(const PeerInfo* peerInfo)
{
    mPeerInfo = peerInfo;
}

}
